package com.hkedou.yuanhuo.adminsystem.business.user.controller;

import com.alibaba.fastjson.JSON;
import com.hkedou.common.view.ResultModel;
import com.hkedou.yuanhuo.adminsystem.business.user.mapper.SysUserMapper;
import com.hkedou.yuanhuo.adminsystem.business.user.model.SysUser;
import com.hkedou.yuanhuo.shiro.constants.AuthConstants;
import com.hkedou.yuanhuo.shiro.redis.RedisTokenManager;
import com.hkedou.yuanhuo.shiro.redis.impl.RedisTokenManagerImpl;
import com.hkedou.yuanhuo.token.Anon;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.UUID;

@Controller
public class LoginController {

    Logger logger= LoggerFactory.getLogger("com.hkedou.adminsystem.login");

    @Autowired
    RedisTokenManager redisTokenManager;


    @Resource
    SysUserMapper sysUserMapper;

    @Anon
    @ResponseBody
    @RequestMapping(value = "/login")
    public ResultModel login(@RequestParam(value = "loginid",required = false)String loginid,
                        @RequestParam(value = "password",required = false)String password, HttpServletRequest request, HttpServletResponse response)
    {

        ResultModel result=new ResultModel();
        result.setStatus(0);
        if(StringUtils.isEmpty(loginid)||StringUtils.isEmpty(password)){
            result.setStatus(1);
            return result;
        }
        logger.debug("--------------login start");

        try{
            SysUser sysUser=sysUserMapper.verification(loginid, password);

            if(sysUser==null){
                result.setStatus(1);
            }else{
                String tokenKey = UUID.randomUUID().toString().replace("-","");
                SysUser tokenValue = sysUser;
                tokenKey=new StringBuffer(AuthConstants.PARAM_TOKEN).append(AuthConstants.DEFAULT_TOKEN_SEPARATOR)
                        .append(tokenValue.getLoginid()).append(AuthConstants.DEFAULT_TOKEN_SEPARATOR).append(tokenKey).toString();
                redisTokenManager.addToken(tokenKey, tokenValue);
                logger.debug("--------- redis add");
                Cookie cookie = new Cookie("access_token", tokenKey);
                response.addCookie(cookie);
            }
        }catch (Exception e){
           logger.error("---error",e);
            result.setStatus(99);
        }
        return result;
    }

    @Anon
    @ResponseBody
    @RequestMapping(value = "/logout")
    public ResultModel logout(HttpServletRequest request, HttpServletResponse response)
    {

        Object token = RedisTokenManagerImpl.getUserValue("access_token");
        if(token!=null){
            redisTokenManager.delToken(token.toString());
        }
        logger.debug("--------logout.token={}",token);
        Cookie cookie=new Cookie("access_token",null); //将之前设置NewCookie值设置为空
        cookie.setMaxAge(0); //设置存活时间为0.此时cookies就会自动注销
        response.addCookie(cookie);
        ResultModel result=new ResultModel();
        result.setStatus(0);
        return (result);
    }


    @RequestMapping(value="/hello",method = RequestMethod.GET)
    @ResponseBody
    public String hello(){
        return JSON.toJSONString("asus");
    }


    @RequestMapping(value="/test",method = RequestMethod.GET)
    @ResponseBody
    public ResultModel test(){
        ResultModel resultModel = new ResultModel();
        resultModel.setData("过滤器测试，不会拦截吧");
        return resultModel;
    }

}
